package com.lemon.cloud.security.service.impl;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CreateCache;
import com.lemon.cloud.admin.feign.AdminFeign;
import com.lemon.cloud.comm.constants.CacheConstants;
import com.lemon.cloud.comm.po.SysRole;
import com.lemon.cloud.comm.po.SysUser;
import com.lemon.cloud.security.enums.GrantTypeEnum;
import com.lemon.cloud.security.service.SmsCodeUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;

public class SmsCodeUserDetailServiceImpl implements SmsCodeUserDetailService {

    @Autowired
    private AdminFeign adminFeign;

    @CreateCache(name = CacheConstants.SYS_USER_DETAIL_BY_MOBILE)
    private Cache<String, SysUser> userCache;

    @CreateCache(name = CacheConstants.SYS_USER_ROLE)
    private Cache<Long, List<SysRole>> roleCache;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser user = userCache.computeIfAbsent(s, (k) -> adminFeign.getByMobile(s).getData());
        if (user==null){
            throw new UsernameNotFoundException("用户不存在！");
        }
        //获取当前用户的角色
        List<SysRole> sysRoles = roleCache.computeIfAbsent(user.getId(), (k) -> adminFeign.getRolesByUserId(user.getId()).getData());
        return getUserDetails(user,sysRoles);
    }

    /**
     * 是否支持此客户端校验
     *
     * @param clientId 目标客户端
     * @return true/false
     */
    @Override
    public boolean support(String clientId, String grantType) {
        return GrantTypeEnum.MOBILE_CODE.getType().equals(grantType);
    }
}
